<?php
	class CategoryAction extends BaseAction{
		public function index(){
			$category = M("Category");
			import("ORG.Util.Page");
			$count = $category->count();
			$page = new Page($count,c('PAGESIZE'));
			$show = $page->show();
			$data = $category->limit($page->firstRow.','.$page->listRows)
							->field("id,pid,category_name,category_info,sort,concat(path,'-',id) as bpath")
							->order("bpath")
							->select();
			//格式化分类名称.
			$this->getCategoryFormat($data);
			$this->assign("list",$data);
			$this->assign('page',$show);
			$this->display();
		}
		
		//实现对一级分类（导航分类）的排序
		public function sort(){
// 			dump($_POST);
			$category = M('Category');
			$data = array();
			$_effectRows = 0;//记录修改影响行数
			for($i = 0; $i < count($_POST['ids']); $i++)
			{
				if(!is_numeric($_POST['sort'][$i])){
					$this->error('请确保输入的是数字！');
					exit();
				}
				$data['sort'] = (int)$_POST['sort'][$i];
				$result = $category->where('id = '.$_POST['ids'][$i])->save($data);
				$_effectRows += $result == false ? 0 : $result;
			}
			if(0 == $_effectRows){
				$this->error('修改分类排序失败或没有需要修改的分类排序！');
			}else{
				$this->success('修改分类排序成功！');
			}
			
		}
		
		public function add(){
			$cat = M('Category');
			$data = $cat->field("category_name,id,pid,concat(path,'-',id) as bpath")
						->order('bpath')
						->select();
			//echo $cat->getLastSql();
			$this->getCategoryFormat($data);
			//dump($data);
			$this->assign('cat',$data);
			$this->display();
		}
		
		public function insert(){
			$cat = D('Category');
			if($cat->create()){
				if($cat->add()){
					$this->success('新增分类成功！');
				}else{
					$this->error('新增分类失败！');
				}
			}else{
				$this->error($cat->getError());
			}
		}
		
		public function edit(){
			if(!empty($_GET['id'])){
				$cat = M('Category');
				$data = $cat->field('id,category_name,category_info,pid')->getById($_GET['id']);
				if(null == $data){
					$this->error('请确认要修改的分类ID正确！');
				}else{
					$parent = $cat->field("category_name,id,pid,concat(path,'-',id) as bpath")
								->order('bpath')
								->select();
					$this->getCategoryFormat($parent);
					$this->assign('cat',$data);
					$this->assign('parent',$parent);
					$this->display();
				}

			}else{
				$this->error('请选择要修改的分类！');
			}

		}
		
		public function update(){
			$cat = D('Category');
			$data = $bpath = $newParent = array();
			
			
			if($data = $cat->create()){
				//判断要修改的分类原先是否是新父类的子类
				//找出要修改分类的path与其id连接,用$bpath暂存
				$bpath = $cat->field("path,concat(path,'-',id) as bpath,pid")->getById($_POST['id']);
				
				//判断分类的父分类有没有变化
				if($bpath['pid'] == $_POST['pid']){//分类的父分类没有变化
					if($cat->save($data)){
						$this->success('更新分类成功！');
					}else{
						$this->error('更新分类失败！');
					}
					exit();
				}
				
				//以下是分类的父分类有变化的情况
				
				
				//得到新父类的path
				if('0' == $_POST['pid']){//如果是顶级分类，设置其path和bpath为'R'
					$newParent['path'] = $newParent['bpath'] = 'R';
					
				}else{
					$newParent = $cat->field("path,concat(path,'-',id) as bpath")->getById($_POST['pid']);
				}
				
				
				
// 				echo 'update zgcms_category set path = replace(path,"'.$bpath['path'].'","'.$newParent['bpath'].'") where path = "'.$bpath['bpath'].'"or path like "'.$bpath['bpath'].'-%"';			
// 				echo $bpath['path'];
// 				dump($bpath);
// 				dump($newParent);
// 				echo 'update zgcms_category set path = replace(path,"'.$bpath['path'].'","'.$newParent['bpath'].'") where path like "'.$bpath['path'].'-%"';
// 				echo strcmp($bpath['bpath'], $newParent['path']);
// 				//substr_compare($bpath,$newParent,0);
// 				echo '<br>';
// 				echo preg_match('#^'.$bpath['bpath'].'-'.'#',$newParent['path']);

				
				//判断要修改父类是否是其子类。判断方法：要修改分类的bpath是否是要修改父类的path的前缀，若是则为其子类
				if($_POST['pid'] == $_POST['id'] || strcmp($bpath['bpath'], $newParent['path']) == 0 || preg_match('#^'.$bpath['bpath'].'-'.'#',$newParent['path']) == 1){
					$this->error('不能将分类移动到其自身或子类下方');
				}else{
// 					echo 'aaaaaaaa';
// 					echo 'update zgcms_category set path = replace(path,"'.$bpath['path'].'","'.$newParent['bpath'].'") where path = "'.$bpath['bpath'].'"or path like "'.$bpath['bpath'].'-%" or id = "'.$_POST['id'].'"';
// 					dump($data);
// 					echo '<br>';
// 					$cat->startTrans();
// 					$cat->save($data);
// 					echo $cat->getLastSql();
// 					$cat->rollback();
					
					$flag = true;
					$cat->startTrans();//开启事务
					//$data['path'] = $newParent['bpath'];
					
					//更新要修改分类除path之外的所有属性
					if(false == $cat->save($data))
						$flag = false;
// 					echo $cat->getLastSql();
// 					$data = array();
// 					$cat->where('path like '.$newParent['bpath'].'-%')->save($data)
					
					//更新要修改分类的所有子类的path
					if(false == $cat->execute('update zgcms_category set path = replace(path,"'.$bpath['path'].'","'.$newParent['bpath'].'") where path = "'.$bpath['bpath'].'"or path like "'.$bpath['bpath'].'-%" or id = "'.$_POST['id'].'"'))
						$flag = false;
//  					echo $cat->getLastSql();
					if(true == $flag){
						$cat->commit();
						$this->success('修改分类成功！');
					}else{
						$cat->rollback();
						$this->error('修改分类失败！');
					}
					
				}
			}else{
				$this->error($cat->getError());
			}
		}
		
		
		public function delete(){
			if(!empty($_GET['id'])){
				$cat = M('Category');
				$bpath = $cat->field("concat(path,'-',id) as bpath")
							->getById($_GET['id']);
				if(false == $bpath){
					$this->error('请确保要删除分类ID正确！');
				}else{
// 					echo 'delete from zgcms_category where id = '.$_GET['id'].' or path = "'.$bpath['bpath'].'" or path like "'.$bpath['bpath'].'-%"';
					$result = $cat->execute('delete from zgcms_category where id = '.$_GET['id'].' or path = "'.$bpath['bpath'].'" or path like "'.$bpath['bpath'].'-%"');
// 					echo $cat->getLastSql();
					if($result){
						$this->success('删除分类及其子类成功！');
					}else {
						$this->error('删除分类失败！');
					}
				}
			}else{
				$this->error('请选择要删除的分类！');
			}
		}
		
		//格式化分类名称，树形分类。
		private function getCategoryFormat(&$data){
			foreach($data as $key => $val){
				$data[$key]['fname'] = 0 == $val['pid'] ? $val['category_name'] : str_repeat('&nbsp;', (count(explode('-', $val['bpath']))-1)*4).'|--'.$val['category_name'];
			}
		}
	}
?>